<template>

  <!--头: 引入 CommHead 子组件-->
  <header class="update-phone-head">
    <CommonHead title="修改用户手机"/>
  </header>

  <br/>

  <!--体: 使用卡片单元格布局修改界面-->
  <section class="update-phone-body">

    <van-cell-group inset>

      <!--手机号: 双绑用户手机号，背景提示字，左图标，垂直居中，可清除，自动获取焦点，关闭提示-->
      <van-field label="手机号" v-model="phone" placeholder="请输入新手机号"
                 left-icon="edit" center clearable autofocus autocomplete="off">

        <template #button>
          <!--按钮: 小号，主要蓝，点击时触发-->
          <van-button size="small" type="primary" @click="updatePhone">保存</van-button>
        </template>

      </van-field>

    </van-cell-group>

  </section>

</template>

<script setup>

import CommonHead from "@/components/CommonHead";
import {UPDATE_PERSONAL} from '@/api/user';
import {useStore} from "vuex";
import router from "@/router";
import {onBeforeMount, shallowRef} from "vue";
import {showFailToast, showSuccessToast} from "vant";
import {SUCCESS} from "@/constant";

/* ==================== data ==================== */

// data: Vuex实例，直接使用useStore()会报错
let vuex = useStore();

// data: 用户主键
const userId = sessionStorage.getItem('userId');

// data: 用户手机号，转为字符串是为了方便正则校验
let phone = shallowRef(router.currentRoute.value.query['phone'] + "");

/* ==================== method ==================== */

// method: 修改用户手机号
async function updatePhone() {

  // 用户手机号规则校验
  if (!/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/.test(phone.value)) {
    showFailToast("手机号码格式不正确");
    return;
  }

  // 异步调用修改用户信息接口
  let result = await UPDATE_PERSONAL({'phone': phone.value});
  let resp = result['data'];
  if (resp.code === SUCCESS) {
    showSuccessToast("修改成功");
    await router.push("/Personal");
  } else {
    showFailToast(resp.message + ': ' + resp.data);
  }
}

/* ==================== beforeMount ==================== */

// beforeMount: DOM挂载前，判断用户是否登录
onBeforeMount(() => {
  if (!vuex.state['loginFlag']) {
    showFailToast('请先登录');
    setTimeout(() => router.push("/LoginByAccount"), 1000);
  }
});

</script>

<style scoped lang="scss">

</style>